package com.restkeeper.store.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.store.dto.AllDishDTO;
import com.restkeeper.store.entity.*;
import com.restkeeper.store.mapper.DishMapper;
import com.restkeeper.utils.SystemCode;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜品服务实现类
 */
@Component
@Service(version = "1.0.0",protocol = "dubbo")
public class DishServiceImp extends ServiceImpl<DishMapper, Dish> implements IDishService{

    /**
     * 菜品停售
     * @param ids
     * @return
     */
    @Override
    public boolean forbiddenSalesStatus(List<String> ids) {
        if(ids==null || ids.isEmpty()){
            throw new BussinessException("没有需要停售的菜品");
        }
        //批量修改菜品为停售状态
        UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(Dish::getStatus,SystemCode.FORBIDDEN).in(Dish::getId,ids);
        return this.update(updateWrapper);
    }

    /**
     * 菜品启售
     * @param ids
     * @return
     */
    @Override
    public boolean enabledSalesStatus(List<String> ids) {
        if(ids==null || ids.isEmpty()){
            throw new BussinessException("没有需要启售的菜品");
        }
        //批量修改菜品为启售状态
        UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(Dish::getStatus,SystemCode.ENABLED).in(Dish::getId,ids);
        return this.update(updateWrapper);
    }

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private ISetmealDishService setmealDishService;

    @Autowired
    private ISetmealService setmealService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean save(Dish dish, List<DishFlavor> flavorList){
        List<Dish> dishList = this.list();
        List<String> dishNames=dishList.stream().map(Dish::getName).collect(Collectors.toList());
        if(dishNames.contains(dish.getName())){
            throw new BussinessException("菜品名称重复");
        }
        this.save(dish);
        //批量插入口味
        flavorList.forEach(flavor->{
            flavor.setDishId(dish.getId());
        });
        dishFlavorService.saveBatch(flavorList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean update(Dish dish, List<DishFlavor> flavorList) {
        this.updateById(dish);
        if(!flavorList.isEmpty()){
            //删除原来口味关系
            QueryWrapper<DishFlavor> dishFlavorQueryWrapper =new QueryWrapper<>();
            dishFlavorQueryWrapper.lambda().eq(DishFlavor::getDishId,dish.getId());
            dishFlavorService.remove(dishFlavorQueryWrapper);
            //建立新的口味关系
            flavorList.forEach(flavor->{
                flavor.setDishId(dish.getId());
            });
            dishFlavorService.saveBatch(flavorList);
        }
        return true;
    }

    @Override
    public List<DishCategory> queryByType(int type) {
        return null;
    }


    @Override
    public List<Dish> findByCode(String code) {
        // TODO:
        return null;
    }

    @Override
    public IPage<Dish> queryPage(Long pageNo, Long pageSise) {
        QueryWrapper<Dish> qw = new QueryWrapper<>();
        qw.orderByDesc("last_update_time");
        IPage<Dish> page = new Page<>(pageNo,pageSise);
        return this.page(page,qw);
    }

    @Override
    public IPage<Dish> queryByName(String name, Long pageNo, Long pageSize) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(name)){
            wrapper.lambda()
                    .like(Dish::getName,name);
        }
        IPage<Dish> page = new Page<>(pageNo,pageSize);
        return this.page(page,wrapper);
    }

    //收银端接口
    @Override
    public IPage<Dish> queryByCategory(String categoryId, Long pageNo, Long pageSize) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Dish::getStatus,SystemCode.ENABLED);
        if(!"all".equals(categoryId)){
            wrapper.lambda()
                    .eq(Dish::getCategoryId,categoryId);
        }
        IPage<Dish> page = new Page<>(pageNo,pageSize);

        return this.page(page,wrapper);
    }

    @Override
    public IPage<AllDishDTO> selectAllDish(long page, long pageSize){
        Page<AllDishDTO> dishPage = new Page<>(page,pageSize);
        return this.baseMapper.selectAllDish(dishPage);
    }

//    @Override
//    @Transactional(rollbackFor = {Exception.class})
//    public boolean updateStatus(List<String> ids,Integer status) {
//        if(ids == null) return false;
//        //修改菜品售卖状态
//        UpdateWrapper<Dish> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.lambda().set(Dish::getStatus,status).in(Dish::getId,ids);
//         //如果是停止售卖,修改菜品所有关联套餐
//        Set<String> setmealSet=new HashSet<>();
//        if(SystemCode.FORBIDDEN==status) {
//            ids.forEach((id) -> {
//                //根据菜品id查询是否存在相关的套餐信息
//                List<String> setMealIds = setmealDishService.selectSetMealIdsByDishId(id);
//                setmealSet.addAll(setMealIds);
//            });
//        }
//            if (setmealSet != null || setmealSet.size()>0){
//                //修改套餐状态为已停售
//                setmealService.updateStatus(new ArrayList<>(setmealSet),SystemCode.FORBIDDEN);
//            }
//           return true;
//    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteDishs(List<String> ids) {
        if(ids == null|| ids.isEmpty()) {
            throw new BussinessException("没有需要删除的菜品");
        }
        return this.removeByIds(ids);
    }

    @Override
    public long getCountByCategory(String categoryId) {
        QueryWrapper<Dish> qw = new QueryWrapper<>();
        qw.lambda()
            .eq(Dish::getCategoryId,categoryId);
        return this.count(qw);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public boolean update(Dish dish, String flavorValue) {
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.lambda()
            .eq(DishFlavor::getDishId,dish.getId());
        DishFlavor dishFlavor = dishFlavorService.getOne(wrapper);
        this.updateById(dish);
        if(dishFlavor != null){
            dishFlavor.setFlavorValue(flavorValue);
            dishFlavorService.updateById(dishFlavor);
        }
        return true;
    }

    @Override
    public List<Map<String,Object>> findEnableDishListInfo(String categoryId, String name) {

        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().select(Dish::getId,Dish::getName,Dish::getStatus,Dish::getPrice);

        if (StringUtils.isNotEmpty(categoryId)){
            queryWrapper.lambda().eq(Dish::getCategoryId,categoryId);
        }
        if (StringUtils.isNotEmpty(name)){
            queryWrapper.lambda().eq(Dish::getName,name);
        }

        queryWrapper.lambda().eq(Dish::getStatus, SystemCode.ENABLED);

        return this.listMaps(queryWrapper);
    }
}
